<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>班级管理</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../css/oksub.css">
</head>
<body>
<div class="ok-body">
    <!--模糊搜索区域-->
    <div class="layui-card">
        <div class="layui-card-header">学生查询条件</div>
        <div class="layui-card-body">
            <div class="layui-row">
                <form class="layui-form layui-form-pane ok-form">

                    <div class="layui-form-item">
                        <label class="layui-form-label">所属专业</label>
                        <div class="layui-input-block">
                            <select name="classify" lay-verify="required" id="profession" lay-filter="changeClass" class="layui-select" lay-search>
                            </select>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">所属班级</label>
                        <div class="layui-input-block">
                            <select name="classify" lay-verify="required" id="classes" lay-filter="changeStudent" class="layui-select" lay-search>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="layui-card-body">
            <div class="layui-row">
                <form class="layui-form layui-col-md12 ok-search">
                    <input class="layui-input" placeholder="学生学号ID" autocomplete="off" name="stuId">
                    <input class="layui-input" placeholder="学生姓名" autocomplete="off" name="stuName">
                    <button class="layui-btn" lay-submit="" lay-filter="searchStudent">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!--数据表格-->
    <table class="layui-hide" id="tableId" lay-filter="tableFilter"></table>
</div>
<!--js逻辑-->
<script src="../../lib/layui/layui.js"></script>
<script src="../../js/model.js"></script>
<script>
    layui.use(["element", "table", "form", "laydate", "okLayer", "okUtils", "okMock","jquery","okNprogress","okMd5"], function () {
        let table = layui.table;
        let form = layui.form;
        let laydate = layui.laydate;
        let okLayer = layui.okLayer;
        let okUtils = layui.okUtils;
        let $=layui.jquery;
        let okNprogress = layui.okNprogress;
        let okMd5 = layui.okMd5;

        let professionId=-1;
        let classesId=-1;

        laydate.render({elem: "#startTime", type: "datetime"});
        laydate.render({elem: "#endTime", type: "datetime"});

        // 获取contentText
        const ctx = function () {
            let pathName = document.location.pathname;
            let index = pathName.substr(1).indexOf("/");
            let result = pathName.substr(0, index + 1);
            return result;
        }();

        okNprogress.start();

        function getAllProfession(success,error){
            $.ajax({
                url: ctx + '/admin/getAllProfessionPage',
                type: 'POST',
                headers:{"token":sessionStorage.getItem("token")},
            }).done(function(datas) {
                var list=datas['data'];
                var option;
                if (list.length!=0){
                    for(var i=0;i<list.length;i++){
                        if (i==0){
                            professionId=list[i]['professionid'];
                        }
                        option+="<option value='"+list[i]['professionid']+"'>"+list[i]['professionname']+"</option>";//拼接option中的内容
                        $("#profession").html(option);//将option的拼接内容加入select中，注意选择器是select的ID
                    }
                }else{
                    professionId=-1;
                }
                form.render('select');//重点：重新渲染select
                success();
            }).fail(function() {
                error();
                console.log("error");
            });
        }

        function getClassesByProfessionId(success,error){
            $.ajax({
                url: ctx + '/admin/getClzaaByProfessionId',
                type: 'POST',
                headers:{"token":sessionStorage.getItem("token")},
                data:{"professionId":professionId}
            }).done(function(datas) {
                var list=datas['data'];
                var option;
                if (list!=null){
                    for(var i=0;i<list.length;i++){
                        if (i==0){
                            classesId=list[i]['clazzid'];
                        }
                        option+="<option value='"+list[i]['clazzid']+"'>"+list[i]['clazzname']+"</option>";//拼接option中的内容
                        $("#classes").html(option);//将option的拼接内容加入select中，注意选择器是select的ID
                    }
                }else{
                    classesId=-1;
                }
                success();
                form.render('select');//重点：重新渲染select
            }).fail(function() {
                console.log("error");
                error();
            });
        }

        getAllProfession(function () {
            getClassesByProfessionId(function () {
                let cla=new CLzaa(classesId,"","","","");
                let stu=new SimpleStudent("","",cla)
                studentTable.reload({
                    url: ctx + '/admin/getStudentByAttributes',
                    where: {"jsonStudent":JSON.stringify(stu)},
                    limit: 20,
                    page: true,
                    toolbar: true,
                    toolbar: "#toolbarTpl",
                    headers:{"token":sessionStorage.getItem("token")},
                    size: "sm",
                });
            },function () {
                console.log("error");
            });
        },function (){
            console.log("error");
        });

        form.on('select(changeClass)',function(data){
            professionId=data.value;
            $("#classes").empty();
            form.render("select");
            getClassesByProfessionId(function () {
                let cla=new CLzaa(classesId,"","","","");
                let stu=new SimpleStudent("","",cla)
                //table重载
                studentTable.reload({
                    url: ctx + '/admin/getStudentByAttributes',
                    where: {"jsonStudent":JSON.stringify(stu)}, //设定异步数据接口的额外参数
                    limit: 20,
                    page: true,
                    toolbar: true,
                    toolbar: "#toolbarTpl",
                    headers:{"token":sessionStorage.getItem("token")},
                    size: "sm",
                });
            },function () {
                console.log("error")
            });
        })

        form.on('select(changeStudent)',function(data){
            classesId=data.value;
            let cla=new CLzaa(classesId,"","","","");
            let stu=new SimpleStudent("","",cla);
            studentTable.reload({
                url: ctx + '/admin/getStudentByAttributes',
                where: {"jsonStudent":JSON.stringify(stu)}, //设定异步数据接口的额外参数
                limit: 20,
                page: true,
                toolbar: true,
                toolbar: "#toolbarTpl",
                headers:{"token":sessionStorage.getItem("token")},
                size: "sm",
            });
        })

        let studentTable = table.render({
            even: true, //开启隔行背景
            elem: '#tableId',
            url: ctx + '/admin/getStudentByAttributes',
            where: {"jsonStudent":JSON.stringify(new SimpleStudent("","",new CLzaa(-1,"","","","")))},
            limit: 20,
            page: true,
            toolbar: true,
            toolbar: "#toolbarTpl",
            size: "sm",
            response:{
                statusCode:200,
            },
            headers:{"token":sessionStorage.getItem("token")},
            cols: [[
                {type: "checkbox", fixed: "left"},
                {field: "stuid", title: "学生ID", width: 160, sort: true},
                {field: "realname", title: "学生名字", width: 160, sort: true,edit: "text"},
                {field: "sex", title: "性别", width: 100, sort: true,edit: "text"},
                {field: "idnumber", title: "身份证号码", width: 160, sort: true,edit: "text"},
                {field: "dateofbirth", title: "出生日期", width: 160, sort: true,edit: "text"},
                {field: "phonenumber", title: "学生电话", width: 160, sort: true,edit: "text"},
                {field: "email", title: "邮箱", width: 160, sort: true,edit: "text"},
                {field: "education", title: "学历", width: 160, sort: true,edit: "text"},
                {field: "graduation", title: "毕业年份", width: 160, sort: true,edit: "text"},
                {field: "marriagestatus", title: "婚姻状况", width: 160, sort: true,edit: "text"},
                {field: "address", title: "住址", width: 160, sort: true,edit: "text"},
                {field: "password", title: "学生密码", width: 160, sort: true,hide:true},
                {field: "photo", title: "学生头像", width: 160, sort: true},
                {field: "classesId", title: "班级ID", width: 160, sort: true,templet: function(d){return d.clzaa? (d.clzaa.clazzid||'') : '';}},
                {field: "classesName", title: "班级名称", width: 200,templet: function(d){return d.clzaa? (d.clzaa.clazzname||'') : '';}},
                {field: "professionid", title: "所属专业ID", width: 100,templet: function(d){return d.clzaa? (d.clzaa.profession.professionid||'') : '';},hide:true},
                {field: "professionName", title: "所属专业名称", width: 200,templet: function(d){return d.clzaa? (d.clzaa.profession.professionname||'') : '';}},
                {title: "操作", width: 100, align: "center", fixed: "right", templet: "#operationTpl"}
            ]],
            done: function (res, curr, count) {
                okNprogress.done();
            },error:function (r) {
                okNprogress.done();
                console.log("错误信息",r)
            }
        });

        form.on("submit(searchStudent)", function (data) {
            var initData =data.field;
            var cla;
            var stu;
            if (initData.stuId==""&&initData.stuName==""){
                cla=new CLzaa(classesId,"","","","");
                stu=new SimpleStudent("","",cla)
            }else{
                stu=new SimpleStudent(initData.stuId,initData.stuName,null)
            }

            studentTable.reload({
                url:ctx+"/admin/getStudentByAttributes",
                where: {"jsonStudent":JSON.stringify(stu)},
                page: {curr: 1}
            });
            return false;
        });

        table.on("toolbar(tableFilter)", function (obj) {
            switch (obj.event) {
                case "batchEnabled":
                    batchEnabled();
                    break;
                case "batchDisabled":
                    batchDisabled();
                    break;
                case "batchDel":
                    batchDel();
                    break;
                case "add":
                    add();
                    break;
            }
        });

        table.on("tool(tableFilter)", function (obj) {
            let data = obj.data;
            switch (obj.event) {
                case "edit":
                    edit(data);
                    break;
                case "del":
                    del(data);
                    break;
                case "resetPwd":
                    resetPwd(data);
                    break;
            }
        });

        function batchEnabled() {
            console.log("666666")
            okLayer.open("批量添加学生", "student-batchInsert.html", "90%", "90%", null, function () {
                // 开始进度条
                okNprogress.start();
                studentTable.reload();
                // 结束进度条
                okNprogress.done();
            });
        }

        function batchDisabled() {
            okLayer.confirm("确定要批量修改吗？", function (index) {
                layer.close(index);
                var checkStatus = table.checkStatus("tableId");
                var rows = checkStatus.data.length;
                if (rows > 0) {
                    var idsStr=checkStatus.data;
                    if (idsStr) {
                        var array = [];
                        for (var i=0;i<rows;i++){
                            array.push(new Student(checkStatus.data[i].stuid,checkStatus.data[i].realname,checkStatus.data[i].password,
                                checkStatus.data[i].sex,checkStatus.data[i].idnumber, checkStatus.data[i].dateofbirth,checkStatus.data[i].photo,
                                checkStatus.data[i].phonenumber,checkStatus.data[i].email,checkStatus.data[i].education,checkStatus.data[i].address,
                                checkStatus.data[i].graduation,checkStatus.data[i].marriagestatus,new CLzaa(checkStatus.data[i].clazzid,"","","")));
                        }

                        $.ajax({
                            url:ctx+'/admin/batchUpdateStudent',
                            type:'POST',
                            data:{"jsonArrayStudent": JSON.stringify(array)},
                            dataType:'json',
                            error:function(){
                                okLayer.redCrossMsg("服务器错误")
                            },
                            success:function(data){
                                if (data.code == 200) {
                                    // 业务正常
                                    okUtils.tableSuccessMsg(data.msg);
                                } else {
                                    // 业务异常
                                    okLayer.yellowSighMsg(data.msg)
                                }
                            }
                        });
                    }
                    return idsStr;
                } else {
                    layer.msg("未选择有效数据", {offset: "t", anim: 6});
                }
            });
        }

        function batchDel() {
            okLayer.confirm("确定要批量删除吗？", function (index) {
                layer.close(index);
                var checkStatus = table.checkStatus("tableId");
                var rows = checkStatus.data.length;
                if (rows > 0) {
                    var idsStr=checkStatus.data;
                    if (idsStr) {
                        var idsStr = "";
                        for (var i = 0; i < checkStatus.data.length; i++) {
                            idsStr += checkStatus.data[i].stuid + ",";
                        }
                        $.ajax({
                            url:ctx+'/admin/batchDelStudent',
                            type:'POST',
                            data:{"students": idsStr},
                            dataType:'json',
                            error:function(){
                                okLayer.redCrossMsg("服务器错误")
                            },
                            success:function(data){
                                if (data.code == 200) {
                                    // 业务正常
                                    okUtils.tableSuccessMsg(data.msg);
                                    okNprogress.done();
                                } else {
                                    // 业务异常
                                    okLayer.yellowSighMsg(data.msg)
                                }
                            }
                        });
                    }
                    return idsStr;
                } else {
                    layer.msg("未选择有效数据", {offset: "t", anim: 6});
                }
            });
        }

        function add() {
            okLayer.open("添加学生", "student-add.html", "90%", "90%", null, function () {
                studentTable.reload();
                okNprogress.done();
            })
        }

        function edit(data) {
            okLayer.open("修改学生", "student-edit.html", "90%", "90%", function (layero) {
                let iframeWin = window[layero.find("iframe")[0]["name"]];
                iframeWin.initForm(data);
            }, function () {
                okNprogress.start();
                studentTable.reload();
                okNprogress.done();
            })
        }

        function resetPwd(data) {
            okLayer.confirm("确定要重置密码吗？", function () {
                var cla=new CLzaa(data.classesId,"","","");
                var stu=new Student(data.stuid,data.realname,okMd5(123456),data.sex,data.idnumber,
                    data.dateofbirth,data.photo,data.phonenumber,data.email,data.education,data.address,
                    data.graduation,data.marriagestatus,cla)
                $.ajax({
                    url:ctx+'/admin/updateStudent',
                    type:'POST',
                    data:{"jsonStudent":JSON.stringify(stu)},
                    dataType:'json',
                    error:function(){
                        okLayer.redCrossMsg("服务器错误")
                    },
                    success:function(data){
                        if (data.code == 200) {
                            // 业务正常
                            okLayer.greenTickMsg(data.msg);
                        } else {
                            // 业务异常
                            okLayer.yellowSighMsg(data.msg)
                        }
                    }
                });
            })
        }

        function del(data) {
            okLayer.confirm("确定要删除吗？", function () {
                okNprogress.start();
                studentTable.reload();
                $.ajax({
                    url:ctx+'/admin/delStudent',
                    type:'POST',
                    data:{"stuId":data.stuid},
                    dataType:'json',
                    error:function(){
                        okLayer.redCrossMsg("服务器错误")
                        okNprogress.done();
                    },
                    success:function(data){
                        if (data.code == 200) {
                            // 业务正常
                            okLayer.greenTickMsg(data.msg);
                        } else {
                            // 业务异常
                            okLayer.yellowSighMsg(data.msg)
                        }
                        okNprogress.done();
                    }
                });
            })
        }
    })
</script>
<!-- 头工具栏模板 -->
<script type="text/html" id="toolbarTpl">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="batchEnabled">批量添加</button>
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="batchDisabled">批量修改</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="batchDel">批量删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="add">添加学生</button>
    </div>
</script>
<!-- 行工具栏模板 -->
<script type="text/html" id="operationTpl">
    <a href="javascript:" title="编辑" lay-event="edit"><i class="layui-icon">&#xe642;</i></a>
    <a href="javascript:" title="删除" lay-event="del"><i class="layui-icon">&#xe640;</i></a>
    <a href="javascript:" title="重置密码" lay-event="resetPwd"><i class="ok-icon">&#xe73f;</i></a>
</script>
<!-- 启用|停用模板 -->
<script type="text/html" id="statusTpl">
    {{#  if(d.status == 0){ }}
    <span class="layui-btn layui-btn-normal layui-btn-xs">已启用</span>
    {{#  } else if(d.status == 1) { }}
    <span class="layui-btn layui-btn-warm layui-btn-xs">已停用</span>
    {{#  } }}
</script>
</body>
</html>
